(function () {
  /** 开奖周期 */
  const period = 10;
  // 截至日期=起始日期+开奖周期(自行定制即可),只需要确保expiryDate正确即可
  const expiryDate = new Date();
  expiryDate.setMinutes(expiryDate.getMinutes() + period);

  function updateCountdown() {
    const now = new Date();
    const diff = expiryDate - now;

    if (diff < 0) {
      clearInterval(intervalId);
      document.getElementById("countdown").textContent = "已开奖";
      return;
    }

    // 计算剩余的天数、小时、分钟和秒数
    const diffDays = Math.floor(diff / (1000 * 60 * 60 * 24));
    const diffHours = Math.floor(
      (diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
    );
    const diffMinutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
    const diffSeconds = Math.floor((diff % (1000 * 60)) / 1000);

    // 更新倒计时文本,这儿开开奖周期长短，如果按小时维度把下面hours注释放开即可
    // document.getElementById("days").textContent = diffDays;
    // document.getElementById("hours").textContent = diffHours;
    document.getElementById("minutes").textContent = diffMinutes;
    document.getElementById("seconds").textContent = diffSeconds;
    document.getElementById("timer").textContent = formatDate(expiryDate);
  }

  // 初始化倒计时显示,每期开奖需要重新计算expiryDate，然后再调用该方法即可
  updateCountdown();

  // 设置定时器，每秒更新一次倒计时
  const intervalId = setInterval(updateCountdown, 1000);

  function formatDate(date) {
    function padZero(num) {
      return num < 10 ? "0" + num : num;
    }

    var year = date.getFullYear();
    var month = padZero(date.getMonth() + 1); // 月份是从0开始的
    var day = padZero(date.getDate());
    var hours = padZero(date.getHours());
    var minutes = padZero(date.getMinutes());
    var seconds = padZero(date.getSeconds());

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  }
})();
